package com.zjz.servlet.user;


import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.zjz.pojo.Role;
import com.zjz.pojo.User;
import com.zjz.service.role.RoleServiceImpl;
import com.zjz.service.user.UserService;
import com.zjz.service.user.UserServiceImpl;
import com.zjz.util.Constants;
import com.zjz.util.PageSupport;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


//实现servlet复用
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("access UserServlet -----------------");
        String newPassword = req.getParameter("newpassword");
        String oldPassword = req.getParameter("oldpassword");
        String method = req.getParameter("method");

        if (newPassword != null) {
            this.updatePwd(req, resp);
        }

        if (oldPassword != null) {
            this.pwdModufy(req, resp);
        }

        if (method.equals("query") && method != null) {
            this.query(req,resp);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 只能修改当前账户的密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从Session里拿ID,获取当前账户
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);

        String newpassword = req.getParameter("newpassword");

        boolean flag;
        if (o != null && !StringUtils.isNullOrEmpty(newpassword)) {
            UserService userService = new UserServiceImpl();
            flag = userService.updatePsd(((User) o).getId(), newpassword);
            if (flag) {
                req.setAttribute("message", "密码修改成功，请退出");
                //密码修改成功，移除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            } else {
                req.setAttribute("message", "密码修改失败");
            }
        } else {
            req.setAttribute("message", "新密码有问题");
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
    }


    // 验证旧密码,session中用户的密码
    public void pwdModufy(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从Session里拿ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");


        // 万能的Mao，一切东西都可以存到map中 --- 结果集
        HashMap<String, String> resultMap = new HashMap<String, String>();


        if (o == null) {
            resultMap.put("resultMap", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) { // 输入的密码为null
            resultMap.put("resultMap", "error");
        } else {
            String userPassword = ((User) o).getUserPassword(); // session中的密码
            if (oldpassword.equals(userPassword)) {
                resultMap.put("resultMap", "true");
            } else {
                resultMap.put("resultMap", "false");
            }
        }

        resp.setContentType("application/json");  // setContentType 设置文本的类型
        PrintWriter writer = resp.getWriter();
        // JSONArray Alibaba的JSON工具类，转换格式的
        /*
         * resultMao={""resultMap","sessionerror","resultMap","error"}
         * Json格式  ={key:value}
         * */
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();


    }

    // 查询用户列表---重点，难点
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        // 查询用户列表
 // 从前端获取数据
        String queryUserName = req.getParameter("queryname");
        String tempUserRole = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");

        // 获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        // 第一次走这个请求，一定是第一页，页面大小固定
        int pageSize = Constants.PAGE_SIZE;
        int currentPageNo = 1;
        int queryUserRole = 0;

        if(queryUserName == null){
            queryUserName ="";
        }

        if(tempUserRole!=null&&!tempUserRole.equals("")){
            queryUserRole = Integer.parseInt(tempUserRole); // 给查询赋值
        }

        if(pageIndex!=null){
            try{
                currentPageNo = Integer.parseInt(pageIndex);
            }catch (Exception e){
                resp.sendRedirect("error.jsp");
            }
        }

        // 获取用户的总数
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);

        // 总页数支持
        PageSupport pageSupport = new PageSupport();

        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = pageSupport.getTotalPageCount();
        // 控制首页和尾页
        // 如果页面要小于1,就到第一页
        if(currentPageNo<=1){
            currentPageNo=1;
        }else if (currentPageNo>totalPageCount){  // 当前页面大于最后一页
            currentPageNo=totalPageCount;
        }


/*

       没用到控制currentpageNo进行跳转，它的作用就是初始显示第一页。。。控制逻辑js处理了。
        else {
            String currentPageNo1 = req.getParameter("currentPageNo");
            if(currentPageNo1!=null&&!currentPageNo1.equals("")){
                currentPageNo=Integer.valueOf(currentPageNo1);
            }

        }

*/

        // 获取用户展示
        List<User> userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);

        req.setAttribute("userList",userList);


        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);

        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);

        // 返回前端
        req.getRequestDispatcher("userlist.jsp").forward(req,resp);


    }



}
